/*
  S.M.A.C.K - An operating system kernel
  Copyright (C) 2010,2011 Mattias Holm and Kristian Rietveld
  For licensing and a full list of authors of the kernel, see the files
  COPYING and AUTHORS.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <syscalls.h>

static int
overwrite_file (const char *filename)
{
  int i;
  int fd;
  int written = 0;
  const char *buffer = "Testing 1 2 3 testing TESTING";

  /* Overwrite file */
  fd = open(filename);
  if (fd < 0)
    {
      printf("overwrite: error: could not open file '%s'\n", filename);
      return fd;
    }

  for (i = 0; i < 128; i++)
    {
      char number[8];

      written += write(fd, buffer, strnlen(buffer, 64));

      snprintf(number, 8, "%d ", i);
      written += write(fd, number, strnlen(number, 8));
    }

  close(fd);

  return written;
}

static int
read_file(const char *filename)
{
  int i;
  int ret;
  int count = 0;
  int fd;
  char buffer[32];

  fd = open(filename);
  if (fd < 0)
    return -1;

  while ((ret = read(fd, buffer, 32)) > 0)
    count += ret;

  close (fd);

  return count;
}

int
main(int argc, char **argv)
{
  int start = -1, end = -1;
  char buf[256];
  int buf_len;
  int in, out;
  int argv0_len = strnlen(argv[0], 256);

  getwd(buf, 256);

  /* Figure out where file name is located */
  for (int i = 0; i < argv0_len + 1; i++)
    {
      if (start == -1)
        {
          if (argv[0][i] == ' ')
            continue;

          start = i;
          continue;
        }
      else if (end == -1)
        {
          if (argv[0][i] != ' ' && argv[0][i] != 0)
            continue;

          end = i;
          break;
        }
    }

  if (start == -1 || end == -1)
    {
      printf("overwrite: error: no filename provided.\n");
      return -1;
    }

  buf_len = strnlen(buf, 256);
  buf[buf_len] = '/';
  strlcpy(buf + buf_len + 1, argv[0] + start, 256);

  out = overwrite_file(buf);
  if (out < 0)
    return -1;

  in = read_file(buf);
  if (in < 0)
    return -1;

  if (in != out)
    printf("test FAILED: out %d bytes, in %d bytes\n", out, in);
  else
    printf("test OK\n");

  return 0;
}
